package com.ebt.m.utils.js;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.text.TextUtils;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.Toast;

import com.ebt.m.AppContext;
import com.ebt.m.AppInitService;
import com.ebt.m.R;
import com.ebt.m.activity.LoginActivity;
import com.ebt.m.activity.WebBaseActivity;
import com.ebt.m.cloud.ActCloudCache;
import com.ebt.m.cloud.DownLoader;
import com.ebt.m.cloud.bean.ApiMyBudinessInfo;
import com.ebt.m.cloud.bean.MyBusinessInfo;
import com.ebt.m.cloud.downloader.DownloadService;
import com.ebt.m.cloud.downloader.callback.DownloadManager;
import com.ebt.m.cloud.downloader.domain.DownloadInfo;
import com.ebt.m.commons.buscomponent.permission.RxPermissions;
import com.ebt.m.commons.buscomponent.thirtylogin.model.ShareListener;
import com.ebt.m.commons.model.data.BaseDataResult;
import com.ebt.m.commons.model.data.Constants;
import com.ebt.m.commons.utils.Logger;
import com.ebt.m.commons.utils.NetUtils;
import com.ebt.m.commons.utils.PrefKit;
import com.ebt.m.commons.utils.RxUtil;
import com.ebt.m.commons.utils.ToastUtil;
import com.ebt.m.data.middle.EBTGetAdviceInfo;
import com.ebt.m.data.rxModel.api.EBTAPI;
import com.ebt.m.data.rxModel.apibean.ShareParms;
import com.ebt.m.event.WaitDialogEvent;
import com.ebt.m.fileExplore.event.FilePickEvent;
import com.ebt.m.policy.ActChoosePolicy;
import com.ebt.m.proposal_v2.dao.request.ParamUpload;
import com.ebt.m.proposal_v2.dao.request.ParamUploadOrc;
import com.ebt.m.proposal_v2.dao.response.ResponseProposalCardInfo;
import com.ebt.m.proposal_v2.dao.response.ResponseTapFile;
import com.ebt.m.proposal_v2.retrofit.ResponseBodyBase;
import com.ebt.m.proposal_v2.retrofit.ResponseError;
import com.ebt.m.proposal_v2.utils.ProposalUtils;
import com.ebt.m.proposal_v2.utils.RxUtils;
import com.ebt.m.share.ShareDialog;
import com.ebt.m.share.ShareUtils;
import com.ebt.m.utils.ConfigData;
import com.ebt.m.utils.FileDownloader;
import com.ebt.m.utils.ImageSelectUtil;
import com.ebt.m.utils.UIHelper;
import com.ebt.m.widget.MDEBTDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * Created by Damon.Han on 2016/12/13 0013.
 *
 * @author Damon
 */
public class JsObject {
    private Context context;
    private Map<String, Object> resultMap = new HashMap<>();
    private WebView webView;

    public Map<String, Object> getResultMap() {
        return resultMap;
    }

    public JsObject(Context context) {
        this.context = context;
    }

    public JsObject(Context context, WebView webView) {
        this.context = context;
        this.webView = webView;
    }

    /**
     * 获取网络状态
     */
    @JavascriptInterface
    public String getNetStatus() {
        int netType = NetUtils.getNetConnectionType(AppContext.getInstance());
        String result = "offline";
        switch (netType) {
            case ConnectivityManager.TYPE_WIFI:
                result = "wifi";
                break;
            case ConnectivityManager.TYPE_MOBILE:
                result = "2g3g4g";
                break;
            default:
                break;
        }
        return result;
    }

    /**
     * “systime”: timestamp
     */
    @JavascriptInterface
    public String getSysTime() {
        long signTime = AppContext.getCurrentTime();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("systime", signTime);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonObject.toString();
    }

    @JavascriptInterface
    public String getToken() {
        if (AppContext.getCurrentUser() == null || AppContext.getCurrentUser().getAccessToken() == null) {
            return null;
        }
        JSONObject jsonObject = new JSONObject();
        String token = AppContext.getCurrentUser().getAccessToken();
//        token = "d48538608ec4485bb8d98e08d6cf3471";
        try {
            jsonObject.put("token", token);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonObject.toString();
    }

    /**
     * native H5的token失效，native将页面跳转到原生登录界面
     */
    @JavascriptInterface
    public void notifyTokenInvalid() {
        // 得到token失效通知后跳转至登录页面
//        Toast.makeText(context, "登录已过期，请重新登录", Toast.LENGTH_SHORT).show();
        context.startActivity(new Intent(context, LoginActivity.class));
    }

    /**
     * 获取地理位置信息
     */
    @JavascriptInterface
    public String getLocationInfo(double longitude, double latitude) {
        return null;
    }

    /**
     * protocol_version:协议版本
     * app_id: app标示;展业家:zyj,宜宝通:ybt
     * app_version:app版本
     * app_version_name:显示给用户的版本提示
     * app_source:app分发渠道
     * app_os:操作系统版本
     * deviceId:设备ID
     *
     * @return
     */
    @JavascriptInterface
    public String getGlobalEnv() {
        String deviceId = PrefKit.getString(AppContext.getInstance(), Constants.DEVICEID_KEY);
        String appVersion = EBTGetAdviceInfo.getApkVersionKey();
        String appVersionName = EBTGetAdviceInfo.getAppVersionName();
        String appOs = EBTGetAdviceInfo.getSystemVersion();
        String appSource = EBTGetAdviceInfo.getMetadata(AppContext.getInstance(), "TD_CHANNEL_ID");
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("protocol_version", "1.0");
            jsonObject.put("app_id", Constants.SIGN_APP_NAME);
            jsonObject.put("app_version", appVersion);
            jsonObject.put("app_version_name", appVersionName);
            jsonObject.put("app_source", appSource);//app分发渠道
            jsonObject.put("app_os", appOs);
            jsonObject.put("deviceId", deviceId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonObject.toString();
    }


    /**
     * 设置我的名片标题中分享地址和编辑地址
     *
     * @param shareUrl
     * @param editCardUrl
     */
    @JavascriptInterface
    public void setMycardUrl(String shareUrl, String editCardUrl) {
        resultMap.put("shareUrl", shareUrl);
        resultMap.put("editCardUrl", editCardUrl);
        Logger.e("shareUrl= " + shareUrl + " \t editCardUrl = " + editCardUrl);
    }

    @JavascriptInterface
    public void notifyBack() {
        if (context != null) {

        }
    }

    @JavascriptInterface
    public void setNativeTitle(String titleName) {
        Logger.e("title= " + titleName);
        if (getActivity() instanceof WebBaseActivity) {
            WebBaseActivity webBaseActivity = (WebBaseActivity) getActivity();
            webBaseActivity.setTitle4Js(titleName);
        }
    }

    @JavascriptInterface
    public void setNativeTitle(String titleName, String url) {
        Logger.e("title= " + titleName + "----url= " + url);
        if ("null".equalsIgnoreCase(url) || "undefined".equalsIgnoreCase(url)) {
            url = null;
        }
        resultMap.put("titleUrl", url);
        if (getActivity() instanceof WebBaseActivity) {
            WebBaseActivity webBaseActivity = (WebBaseActivity) getActivity();
            webBaseActivity.setTitle4Js(titleName);
        }
    }

    @JavascriptInterface
    public void openWebview(String pdfUrl, String fileName) {
        resultMap.put("pdf_url", pdfUrl);
        //open pdf
        if (pdfUrl == null || pdfUrl.equalsIgnoreCase("") || pdfUrl.equalsIgnoreCase("undefined")) {
            return;
        }
        FileDownloader fileDownloader = new FileDownloader(getActivity(), null);
        fileDownloader.downLoadPdf(pdfUrl, fileName);

    }

    @JavascriptInterface
    public void closeWebview(String viewName) {
        Logger.e("title= " + viewName);
        resultMap.put("pageTitle", viewName);
        Activity activity = getActivity();
        if (activity != null) {
            activity.finish();
        }
    }

    /**
     * 调用分享功能
     */
    @JavascriptInterface
    public void share(String url, String title, String subTitle, String imgUrl) {
        Activity activity = getActivity();
        if (activity == null) {
            return;
        }
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                share(activity, url, title, subTitle, imgUrl, new ArrayList<>());
            }
        });
    }

    /**
     * 调用分享功能(高级)
     * 新增方法，shareAdvance  比以前的share方法新增了一个zone参数，标识可分享区域，数组形式：['wx','wxFriend','qq','qqZone']
     */
    @JavascriptInterface
    public void shareAdvance(String url, String title, String subTitle, String imgUrl, String zone) {
        Activity activity = getActivity();
        if (activity == null) {
            return;
        }
        try {
            JSONArray jsonArray = new JSONArray(zone);
            //根据zone数组中的值确定可以分享到哪个平台
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    share(activity, url, title, subTitle, imgUrl, new ArrayList<>());
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @JavascriptInterface
    public String getAgentId() {
        JSONObject jsonObject = new JSONObject();
        String agentId = AppContext.getCurrentUser().getUserId() + "";
        try {
            jsonObject.put("agentId", agentId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonObject.toString();
    }

    /**
     * H5调用local打开本地产品
     *
     * @param productId
     */
    @JavascriptInterface
    public void toProductNativePage(int productId) {
        JsObjectUtil jsObjectUtil = new JsObjectUtil();
        jsObjectUtil.openProduct(productId);
    }

    /**
     * 本地返回事件按钮
     *
     * @param methodName
     */
    @JavascriptInterface
    public void callNativeReturn(String methodName) {
        Logger.e("callNativeReturn: " + methodName);
        resultMap.put("methodName", methodName);
    }

    /**
     * 本地返回事件按钮取消
     */
    @JavascriptInterface
    public void cancelNativeReturn() {
        resultMap.remove("methodName");
    }

    /**
     * 清空webview浏览记录
     */
    @JavascriptInterface
    public void clearHistory() {
        if (this.webView != null) {
            webView.post(new Runnable() {
                @Override
                public void run() {
                    webView.clearHistory();
                }
            });
        }
    }

    private void share(Activity activity, String url, String title, String subTitle, String imgUrl, List<String> hideList) {
        Context appContext = activity.getApplicationContext();
        ShareListener shareListener = new ShareListener() {
            @Override
            public void onShareError(String platform, String errorInfo) {
                if (!TextUtils.isEmpty(errorInfo)) {
                    Toast.makeText(appContext, errorInfo, Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(appContext, ShareUtils.getZhFromEn(platform, appContext)
                            + appContext.getString(R.string.share_failed), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onShareComplete(String platform) {
                Toast.makeText(appContext, ShareUtils.getZhFromEn(platform, appContext)
                        + appContext.getString(R.string.share_completed), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onShareCancel(String platform) {
                Toast.makeText(appContext, ShareUtils.getZhFromEn(platform, appContext)
                        + appContext.getString(R.string.share_canceled), Toast.LENGTH_SHORT).show();
            }
        };
        openShare(activity, url, title, subTitle, imgUrl, hideList, shareListener, null);
    }

    /**
     * 打开分享对话框
     *
     * @param activity
     * @param url
     * @param title
     * @param subTitle
     * @param imgUrl
     * @param hideList      不需要分享的平台
     * @param shareListener
     */
    private void openShare(Activity activity, String url, String title, String subTitle, String imgUrl, List<String> hideList, ShareListener shareListener, ShareDialog.OnBeforeShareListener onBeforeShareListener) {
        try {
            new ShareDialog.Builder(activity)
                    .setShareTitle(title)
                    .setShareContent(subTitle)
                    .setShareUrl(url)
                    .setShareUrlWeXin(url)
                    .setShareImagePath(imgUrl)
                    .setHidePlatformList(hideList)
                    .setShareListener(shareListener)
                    .setDialogDismissIfShareSuccess()
                    .setBeforeShareListener(onBeforeShareListener)
                    .create()
                    .show();
            EventBus.getDefault().post(shareListener);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Activity getActivity() {
        while (!(context instanceof Activity) && context instanceof ContextWrapper) {
            context = ((ContextWrapper) context).getBaseContext();
        }
        if (context instanceof WebBaseActivity) {
            return (WebBaseActivity) context;
        }
        if (context instanceof Activity) {
            return (Activity) context;
        }
        return null;
    }

    public void registerForEventBus() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    public void unregisterForEventBus() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    private String ossBucketName;
    private String ossDiskPath;
    private String identify;
    private String cbUploadImg;

    //附件上传
    @JavascriptInterface
    public void uploadImg(String params) {
        try {
            JSONObject myJsonObject = new JSONObject(params);
            //1.获取网页传过来的值
            if (myJsonObject.has("ossBucketName")) {
                ossBucketName = myJsonObject.getString("ossBucketName");
            }
            if (myJsonObject.has("ossDiskPath")) {
                ossDiskPath = myJsonObject.getString("ossDiskPath");
            }
            if (myJsonObject.has("identify")) {
                identify = myJsonObject.getString("identify");
            }
            if (myJsonObject.has("cbUploadImg")) {
                cbUploadImg = myJsonObject.getString("cbUploadImg");
            }

            //2.选择附件
            String[] menu_messages = new String[]{"拍照", "图库"/*, "其他"*/};
            MDEBTDialog mMenuDialog = new MDEBTDialog.Builder(context)
                    .setMessages(menu_messages)
                    .setOnItemClickListener(new MDEBTDialog.OnItemClickListener() {
                        @Override
                        public void onItemClicked(int index) {
                            switch (index) {
                                case 0:
                                    onCamera(REQUEST_CODE_CAMERA);
                                    break;
                                case 1:
                                    onImageAlbum(REQUEST_CODE_CAPTURE);
                                    break;
                            }
                        }
                    }).setShowTitle(false)
                    .setShowButtons(false).create();
            mMenuDialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static final int REQUEST_CODE_CAMERA = 1111;
    public static final int REQUEST_CODE_CAPTURE = 2222;
    public static final int REQUEST_CODE_CAMERA_ID = 3333;
    public static final int REQUEST_CODE_CAPTURE_ID = 4444;
    private String mCameraTarget;

    private RxPermissions rxPermissions;

    public void onCamera(int requestCode) {

        if (rxPermissions == null) {
            rxPermissions = new RxPermissions((Activity) context);
        }

        rxPermissions.request(Manifest.permission.CAMERA)
                .subscribe(permission -> {
                    if (permission) {
                        String dir = ImageSelectUtil.getImageCacheDir();
                        if (dir != null && !"".equals(dir)) {
                            String fileName = ImageSelectUtil.getFileName(0, null);
                            mCameraTarget = dir + "/" + fileName;
                            File targetFile = ImageSelectUtil.getFile(dir, fileName);
                            ImageSelectUtil.openCamera((Activity) context, targetFile, requestCode);
                        } else {
                            Toast.makeText(context, "SD卡不存在", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        UIHelper.makeToast(context, "请在设置中为" + context.getResources().getString(R.string.app_name) + "开启相机权限");
                    }
                });
    }

    public void onImageAlbum(int requestCode) {
        ImageSelectUtil.openAlbum((Activity) context, requestCode);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(FilePickEvent event) {
        if (event == null) {
            return;
        }

        File file = null;
        switch (event.from) {
            case FilePickEvent.FromFilePicker:
                file = event.file;
                break;
            case FilePickEvent.FromCamera:
                if (!TextUtils.isEmpty(mCameraTarget)) {
                    file = new File(mCameraTarget);
                }
                break;
            case FilePickEvent.FromAlbum:
                file = event.file;
                break;
        }

        if (file == null) {
            return;
        }
        //3.压缩文件

        Luban.with(context)
                .load(file)                                     // 传人要压缩的图片列表
                .ignoreBy(300)                                  // 忽略不压缩图片的大小
                .setTargetDir(getFilePath())                    // 设置压缩后文件存储位置
                .setCompressListener(new OnCompressListener() { //设置回调
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onSuccess(File file) {
                        //4.上传附件
                        upload(file, event.requestCode);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                }).launch();    //启动压缩
    }

    private void upload(File file, int requestCode) {
        switch (requestCode) {
            case REQUEST_CODE_CAMERA:
            case REQUEST_CODE_CAPTURE:
                uploadAttachment(file);
                break;
            case REQUEST_CODE_CAMERA_ID:
            case REQUEST_CODE_CAPTURE_ID:
                uploadID(file);
                break;
        }
    }

    private void uploadAttachment(File file) {

        EBTAPI mProposalApi = AppInitService.getEbtApi();
        MultipartBody.Part filePart = generateMultipartBody("file", file.getName(), file.getAbsolutePath());
        EventBus.getDefault().post(new WaitDialogEvent(true));
        RxUtils.compose(mProposalApi.updateProposalTapToOSS(filePart, "", ossBucketName, ossDiskPath)).subscribe(
                new Observer<ResponseBodyBase<ResponseTapFile>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseBodyBase<ResponseTapFile> responseTapFileResponseBodyBase) {
                        EventBus.getDefault().post(new WaitDialogEvent(false));
                        if (responseTapFileResponseBodyBase == null
                                || responseTapFileResponseBodyBase.data == null) {
                            Toast.makeText(context, context.getString(R.string.network_fail), Toast.LENGTH_SHORT).show();
                        }
                        ResponseTapFile data = responseTapFileResponseBodyBase.data;
                        if (webView != null) {
                            try {
                                ParamUpload paramUpload = new ParamUpload(data, identify);
                                Gson gson = new Gson();
                                String ret = gson.toJson(paramUpload);
                                webView.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        webView.loadUrl("javascript:" + cbUploadImg + "(" + ret + ")");
                                    }
                                });
                            } catch (Exception e) {
                                Toast.makeText(context, context.getString(R.string.network_fail) + e.getMessage(), Toast.LENGTH_SHORT).show();
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        EventBus.getDefault().post(new WaitDialogEvent(false));
                        e.printStackTrace();
                        if (e.getMessage() != null) {
                            try {
                                Gson gson = new Gson();
                                ResponseError error = gson.fromJson(e.getMessage(), ResponseError.class);
                                Toast.makeText(context, error.message, Toast.LENGTH_SHORT).show();
                            } catch (Exception e1) {
                                Toast.makeText(context, context.getString(R.string.network_fail), Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Toast.makeText(context, context.getString(R.string.network_fail), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onComplete() {
                        EventBus.getDefault().post(new WaitDialogEvent(false));
                    }
                });

    }

    //上传图片
    private void uploadID(File file) {
        EBTAPI mProposalApi = AppInitService.getEbtApi();
        MultipartBody.Part filePart = generateMultipartBody("file", file.getName(), file.getAbsolutePath());
        EventBus.getDefault().post(new WaitDialogEvent(true));
        RxUtils.compose(mProposalApi.uploadIDPic(ocrApi, filePart, ocrSide)).subscribe(
                new Observer<ResponseBodyBase<ResponseProposalCardInfo>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseBodyBase<ResponseProposalCardInfo> responseBody) {
                        EventBus.getDefault().post(new WaitDialogEvent(false));
                        if (responseBody == null) {
                            Toast.makeText(context, context.getString(R.string.network_fail), Toast.LENGTH_SHORT).show();
                        } else {
                            if (responseBody.data == null) {
                                if (responseBody.error != null && responseBody.error.message != null) {
                                    Toast.makeText(context, responseBody.error.message, Toast.LENGTH_SHORT).show();
                                } else {
                                    Toast.makeText(context, context.getString(R.string.network_fail), Toast.LENGTH_SHORT).show();
                                }
                            }
                        }
                        ResponseProposalCardInfo data = responseBody.data;
                        if (webView != null) {
                            try {
                                ParamUploadOrc paramUpload = new ParamUploadOrc(data, ocrIdentify);
                                Gson gson = new Gson();
                                String ret = gson.toJson(paramUpload);
                                webView.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        webView.loadUrl("javascript:" + ocrCbUploadImg + "(" + ret + ")");
                                    }
                                });
                            } catch (Exception e) {
                                Toast.makeText(context, context.getString(R.string.network_fail) + e.getMessage(), Toast.LENGTH_SHORT).show();
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        EventBus.getDefault().post(new WaitDialogEvent(false));
                        e.printStackTrace();
                        if (e.getMessage() != null) {
                            try {
                                Gson gson = new Gson();
                                ResponseError error = gson.fromJson(e.getMessage(), ResponseError.class);
                                Toast.makeText(context, error.message, Toast.LENGTH_SHORT).show();
                            } catch (Exception e1) {
                                Toast.makeText(context, context.getString(R.string.network_fail), Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Toast.makeText(context, context.getString(R.string.network_fail), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onComplete() {
                        EventBus.getDefault().post(new WaitDialogEvent(false));
                    }
                });
    }

    private String getFilePath() {
        File f = new File(ConfigData.Compressed_pic_PATH);
        if (!f.exists()) {
            f.mkdir();
        }
        return ConfigData.Compressed_pic_PATH;
    }


    public MultipartBody.Part generateMultipartBody(String name, String fileName, String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            return null;
        }
        File uploadFile = new File(filePath);
        if (!uploadFile.exists()) {
            return null;
        }
        RequestBody requestFileBody = RequestBody.create(MediaType.parse("multipart/form-data"), new File(filePath));
        return MultipartBody.Part.createFormData(name, fileName, requestFileBody);
    }

    //身份证识别
    private String ocrApi;
    private String ocrSide;
    private String ocrIdentify;
    private String ocrCbUploadImg;


    @JavascriptInterface
    public void uploadImgOcr(String params) {
        try {
            JSONObject myJsonObject = new JSONObject(params);
            //1.获取网页传过来的值
            if (myJsonObject.has("api")) {
                ocrApi = myJsonObject.getString("api");
            }
            if (myJsonObject.has("side")) {
                ocrSide = myJsonObject.getString("side");
            }
            if (myJsonObject.has("identify")) {
                ocrIdentify = myJsonObject.getString("identify");
            }
            if (myJsonObject.has("cbUploadImg")) {
                ocrCbUploadImg = myJsonObject.getString("cbUploadImg");
            }

            //2.选择附件
            String[] menu_messages = new String[]{"拍照", "图库"/*, "其他"*/};
            MDEBTDialog mMenuDialog = new MDEBTDialog.Builder(context)
                    .setMessages(menu_messages)
                    .setOnItemClickListener(new MDEBTDialog.OnItemClickListener() {
                        @Override
                        public void onItemClicked(int index) {
                            switch (index) {
                                case 0:
                                    onCamera(REQUEST_CODE_CAMERA_ID);
                                    break;
                                case 1:
                                    onImageAlbum(REQUEST_CODE_CAPTURE_ID);
                                    break;
                            }
                        }
                    }).setShowTitle(false)
                    .setShowButtons(false).create();
            mMenuDialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @JavascriptInterface
    public void shareCallBack(String params) {
        try {
            Gson gson = new Gson();
            ShareParms shareParms = gson.fromJson(params, ShareParms.class);
            Activity activity = getActivity();
            if (activity == null || shareParms == null) {
                return;
            }
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    List<String> hideList = new ArrayList<>();
                    hideList.add(ShareDialog.COPY_LINK);
                    hideList.add(ShareDialog.QZONE);
                    hideList.add(ShareDialog.WE_CHAT_MOMENTS);
                    String cbTag = shareParms.cbTag;
                    if (!TextUtils.isEmpty(cbTag) && "shareSigning".equals(cbTag)) {
                        hideList.add(ShareDialog.QQ);
                    }
                    openShare(activity, shareParms.url, shareParms.title, shareParms.subTitle, shareParms.imgUrl, hideList, new ShareListener() {

                        @Override
                        public void onShareError(String platform, String errorInfo) {
                            if (!TextUtils.isEmpty(errorInfo)) {
                                Toast.makeText(activity, errorInfo, Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(activity, ShareUtils.getZhFromEn(platform, activity) + activity.getString(R.string.share_failed), Toast.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void onShareComplete(String platform) {
                        }

                        @Override
                        public void onShareCancel(String platform) {
                            Logger.e("onShareCancel===分享取消");
                            Toast.makeText(activity, ShareUtils.getZhFromEn(platform, activity) + activity.getString(R.string.share_canceled), Toast.LENGTH_SHORT).show();
                        }
                    }, new ShareDialog.OnBeforeShareListener() {
                        @Override
                        public void doBeforeShare() {

                            //20180612
                            String cbTag = shareParms.cbTag;
                            if (!TextUtils.isEmpty(cbTag) && "shareSigning".equals(cbTag)) {
                                try {
                                    EBTAPI ebtapi = AppInitService.getEbtApi();
                                    if (TextUtils.isEmpty(shareParms.policyId)) {
                                        return;
                                    }

                                    ebtapi.shareSigning(Integer.valueOf(shareParms.policyId)).compose(RxUtil.rxSchedulerHelper()).subscribe(new Consumer<BaseDataResult>() {
                                        @Override
                                        public void accept(BaseDataResult baseDataResult) throws Exception {
                                            if (baseDataResult.getError() != null) {
                                                String msg = baseDataResult.getError().message;
                                                Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show();
                                            } else {
                                                //20180612
                                                if (shareParms.redirectUrl.equalsIgnoreCase("closeWebview")) {
                                                    //关闭ActChoosePolicy其上的activity后关闭自己
                                                    //Intent intent = new Intent(activity, ActChoosePolicy.class);
                                                    //intent.putExtra(ActChoosePolicy.TAG_EXIT, true);
                                                    //activity.startActivity(intent);
                                                    activity.finish();
                                                } else if (webView != null && !TextUtils.isEmpty(shareParms.redirectUrl)) {
                                                    webView.post(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            webView.loadUrl(shareParms.redirectUrl);
                                                        }
                                                    });
                                                }
                                            }
                                        }
                                    }, new Consumer<Throwable>() {
                                        @Override
                                        public void accept(Throwable throwable) throws Exception {
                                            throwable.printStackTrace();
                                            NetUtils.checkHttpException(activity, throwable);
                                        }
                                    });
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    Toast.makeText(activity, activity.getString(R.string.network_fail), Toast.LENGTH_SHORT).show();
                                }
                            }

                        }
                    });
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @JavascriptInterface
    public void openNativeProList() {
        context.startActivity(new Intent(context, ActChoosePolicy.class));
    }

    /**
     * 16、分享链接
     *
     * @param params
     */
    @JavascriptInterface
    public void shareWithCopy(String params) {
        Activity activity = getActivity();
        if (activity == null) {
            return;
        }
        try {
            Gson gson = new Gson();
            ShareParms shareParms = gson.fromJson(params, ShareParms.class);
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    List<String> hideList = new ArrayList<>();
                    hideList.add(ShareDialog.QZONE);
                    share(activity, shareParms.url, shareParms.title, shareParms.subTitle, shareParms.imgUrl, hideList);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 17.加入下载
     * 分享参数对象
     */
    @JavascriptInterface
    public String nativeDL(String params) {
        try {
            DownLoader downLoader = new DownLoader(getActivity());
            Gson gson = new Gson();
            List<ApiMyBudinessInfo> list = gson.fromJson(params, new TypeToken<List<ApiMyBudinessInfo>>() {
            }.getType());
            for (int i = 0; i < list.size(); i++) {
                ApiMyBudinessInfo apiMyBudinessInfo = list.get(i);
                if (!TextUtils.isEmpty(apiMyBudinessInfo.getSrc())) {
                    String fileType = apiMyBudinessInfo.getSrc().substring(apiMyBudinessInfo.getSrc().lastIndexOf("."), apiMyBudinessInfo.getSrc().length());
                    MyBusinessInfo downloadInfo = new MyBusinessInfo(apiMyBudinessInfo.getId(), apiMyBudinessInfo.getTitle() + fileType, apiMyBudinessInfo.getCover(), apiMyBudinessInfo.getSrc());
                    downLoader.beginDownload(apiMyBudinessInfo.getId(), downloadInfo);
                }
            }
            String dls = getNativeDLList();
            return dls;
        } catch (Exception e) {
            e.printStackTrace();
        }
        ToastUtil.show(getActivity(), "已添加到缓存列表");
        return "";
    }

    /**
     * 18.获取下载链接
     * 分享参数对象
     */
    @JavascriptInterface
    public String getNativeDLList() {
        try {
            DownloadManager downloadManager = DownloadService.getDownloadManager(getActivity().getApplicationContext());
            List<DownloadInfo> downloadInfos = downloadManager.findAllDownloaded();
            List<DownloadInfo> downloadingInfos = downloadManager.findAllDownloading();
            Map<String, String> map = new HashMap<>();
            for (int i = 0; i < downloadInfos.size(); i++) {
                map.put(downloadInfos.get(i).getSourceId() + "", downloadInfos.get(i).getName());
            }
            for (int i = 0; i < downloadingInfos.size(); i++) {
                map.put(downloadingInfos.get(i).getSourceId() + "", downloadingInfos.get(i).getName());
            }
            JSONObject jsonObject = new JSONObject();
            JSONArray array = new JSONArray();
            for (String key : map.keySet()) {
                JSONObject jo = new JSONObject();
                jo.put("id", key);
                jo.put("title", map.get(key));
                array.put(jo);
            }
            jsonObject.put("data", array);
            return jsonObject.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 19.调起缓存页面
     * 分享参数对象
     */
    @JavascriptInterface
    public void openNativePage(String params) {
        try {
            JSONObject myJsonObject = new JSONObject(params);
            //1.获取网页传过来的值
            if (myJsonObject.has("page")) {
                String page = myJsonObject.getString("page");
                if (!TextUtils.isEmpty(page)) {
                    switch (page) {
                        //下载缓存页面
                        case "dl":
                            context.startActivity(new Intent(context, ActCloudCache.class));
                            break;
                        default:
                            break;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 21.获取本地视频地址
     */
    @JavascriptInterface
    public String getLocalVideo(String params) {
        JSONObject resultData = new JSONObject();
        try {
            JSONObject myJsonObject = new JSONObject(params);
            //1.获取网页传过来的值
            if (myJsonObject.has("id")) {
                int id = myJsonObject.getInt("id");
                DownloadManager downloadManager = DownloadService.getDownloadManager(getActivity().getApplicationContext());
                DownloadInfo downloadInfo = downloadManager.getDownloadBySourceId(id);
                if (downloadInfo == null) {
                    return "";
                }
                String path = downloadInfo.getPath();
                JSONObject resultUrl = new JSONObject();
                resultUrl.put("url", path);
                resultData.put("data", resultUrl);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultData.toString();
    }

    /**
     * 22.创建计划书
     */
    @JavascriptInterface
    public void createProposal(String params) {
        try {
            JSONObject myJsonObject = new JSONObject(params);
            //1.获取网页传过来的值
            if (myJsonObject.has("proid")) {
                //产品id
                int id = myJsonObject.getInt("proid");
                if (id > 0) {
                    ProposalUtils.startMakingProposalFromDynamic(getActivity(), id);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    long firstTime = 0;

    /**
     * 23、分享多图到朋友圈
     *
     * @param params
     */
    @JavascriptInterface
    public void shareWithImgs(String params) {
        Activity activity = getActivity();
        if (activity == null) {
            return;
        }
        long secondTime = System.currentTimeMillis();
        if (secondTime - firstTime < 3000) {
            firstTime = secondTime;
            return;
        }
        ToastUtil.show(activity, "请稍候...");
        try {
            JSONObject myJsonObject = new JSONObject(params);
            String imgsArr[] = null;
            if (myJsonObject.has("imgsArr")) {
                JSONArray jsonArray = myJsonObject.getJSONArray("imgsArr");
                if (jsonArray.length() > 0) {
                    imgsArr = new String[jsonArray.length()];
                    for (int i = 0; i < jsonArray.length(); i++) {
                        String imgStr = jsonArray.getString(i);
                        imgsArr[i] = imgStr;
                    }
                }
            }
            String cbTag = null;
            ShareUtils shareUtils = new ShareUtils();
            /*标识调用模块*/
            if (myJsonObject.has("cbTag")) {
                cbTag = myJsonObject.getString("cbTag");
                if (imgsArr != null && imgsArr.length > 0 && "timelineAssistant".equalsIgnoreCase(cbTag)) {
                    shareUtils.shareImgs(activity, 1, imgsArr, "", "wchat");
                }
            }


            String callback = null;
            String callbackParams = null;
            /*转发后的回调方法*/
            if (myJsonObject.has("callback")) {
                callback = myJsonObject.getString("callback");
            }
            /*回调函数参数*/
            if (myJsonObject.has("cbParams")) {
                callbackParams = myJsonObject.getString("cbParams");
            }
            if (!TextUtils.isEmpty(callback) && webView != null) {
                shareUtils.afterShare(webView, callback, callbackParams);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 24.解决js直接调用摄像头拍照问题
     */
    @JavascriptInterface
    public void openCamera(String string) {
        try {
            resultMap.put("openCamera", "openCamera");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
